package bosc.cn.service.impl;

import bosc.cn.controller.dto.RustVerifyReqDTO;
import bosc.cn.controller.dto.RustVerifyResDTO;
import bosc.cn.excception.BusinessException;
import bosc.cn.service.RustVerifyService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service("rustVerifyService")
@Slf4j
public class RustVerifyServiceImpl implements RustVerifyService {

    @Value("${rust.verify.url}")
    private String rustVerifyUrl;

    @Autowired
    @Qualifier("unSSLRestTemplate")
    private RestTemplate restTemplate;

    //@Override
    //public RustVerifyResDTO verify(RustVerifyReqDTO rustVerify) {
    //    RustVerifyResDTO rustVerifyRes = new RustVerifyResDTO();
    //    rustVerifyRes.setValid(true);
    //    return rustVerifyRes;
    //}


    @Override
    public RustVerifyResDTO verify(RustVerifyReqDTO rustVerify) {

        try {
            log.info("rust签名验证入参: {}", JSON.toJSONString(rustVerify));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

            HttpEntity<Object> entity = new HttpEntity<>(rustVerify, headers);

            // 从配置文件读取 rustVerifyUrl，若未配置默认使用本地地址
            log.info("Rust签名验证服务调用路径: {}", rustVerifyUrl);

            // 开始计时
            long start = System.currentTimeMillis();

            ResponseEntity<String> response = restTemplate.exchange(
                    rustVerifyUrl,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
            // 结束计时
            long end = System.currentTimeMillis();
            log.info("Rust签名服务响应耗时: {} ms", (end - start));

            String body = response.getBody();
            log.info("rust签名返回: {}", body);

            if ("200".equals(String.valueOf(response.getStatusCodeValue()))) {
                return JSON.parseObject(body, RustVerifyResDTO.class);
            } else {
                throw new BusinessException("Rust签名服务调用失败，状态码：" + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("Rust签名验证服务调用异常: {}", e.getMessage(), e);
            throw new BusinessException("Rust签名验证服务调用异常：" + e.getMessage());
        }
    }
}
